// 图表工具函数 - 多个页面共享的图表相关功能

/**
 * 防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} wait - 等待时间（毫秒）
 * @returns {Function} - 防抖后的函数
 */
function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

/**
 * 复制代码到剪贴板
 * @param {string} code - 要复制的代码
 * @param {HTMLElement} button - 触发复制的按钮元素（用于更新UI反馈）
 * @returns {Promise<boolean>} - 是否复制成功
 */
async function copyCodeToClipboard(code, button = null) {
  try {
    await navigator.clipboard.writeText(code);
    
    // 如果提供了按钮，更新UI反馈
    if (button) {
      const originalContent = button.innerHTML;
      const originalBg = button.style.backgroundColor;
      const originalColor = button.style.color;
      
      // 显示复制成功的UI
      button.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>';
      button.style.backgroundColor = '#4caf50';
      button.style.color = 'white';
      button.classList.add('copied');
      
      // 恢复原UI
      setTimeout(() => {
        button.innerHTML = originalContent;
        button.style.backgroundColor = originalBg;
        button.style.color = originalColor;
        button.classList.remove('copied');
      }, 2000);
    }
    
    return true;
  } catch (error) {
    console.error('复制失败:', error);
    return false;
  }
}

/**
 * 图表缩放控制器
 */
class ZoomController {
  constructor(previewPanelId,previewElementId, zoomInBtnId, zoomOutBtnId, resetZoomBtnId = null, closeBtnId = null) {
    this.previewPanel = document.getElementById(previewPanelId);
    this.previewElement = document.getElementById(previewElementId);
    this.zoomInBtn = document.getElementById(zoomInBtnId);
    this.zoomOutBtn = document.getElementById(zoomOutBtnId);
    this.resetZoomBtn = resetZoomBtnId ? document.getElementById(resetZoomBtnId) : null;
    this.closeBtn = closeBtnId ? document.getElementById(closeBtnId) : null;
    this.currentZoom = 1; // 当前缩放比例
    this.minZoom = 0.3; // 最小缩放比例（更小）
    this.maxZoom = 5; // 最大缩放比例（更大）
    this.zoomStep = 0.1; // 缩放步长
    this.modalThreshold = 1.5; // 模态框触发阈值
    this.isModal = false; // 是否处于模态状态
    
    // 初始化
    this.init();
  }
  
  // 初始化缩放控制
  init() {
    if (!this.previewElement || !this.zoomInBtn || !this.zoomOutBtn) {
      console.warn('缩放控制元素不存在，缩放功能未初始化');
      return;
    }
    
    // 添加事件监听器
    this.zoomInBtn.addEventListener('click', () => this.zoomIn());
    this.zoomOutBtn.addEventListener('click', () => this.zoomOut());
    
    if (this.resetZoomBtn) {
      this.resetZoomBtn.addEventListener('click', () => this.resetZoom());
    }
    
    if (this.closeBtn) {
      this.closeBtn.addEventListener('click', () => this.closeModal());
    }
    
    // 初始化缩放状态
    this.updateZoomState();
  }
  
  // 放大
  zoomIn() {
    if (this.currentZoom < this.maxZoom) {
      this.currentZoom += this.zoomStep;
      
      // 检查是否需要进入模态状态
      if (this.currentZoom > this.modalThreshold && !this.isModal) {
        this.enterModal();
      }
      
      this.updateZoom();
    }
  }
  
  // 缩小
  zoomOut() {
    if (this.currentZoom > this.minZoom) {
      this.currentZoom -= this.zoomStep;
      
      // 更新缩放显示，但不自动退出模态状态
      this.updateZoom();
    }
  }
  
  // 重置缩放
  resetZoom() {
    this.currentZoom = 1;
    
    // 如果处于模态状态，退出模态状态
    if (this.isModal) {
      this.exitModal();
    }
    
    this.updateZoom();
  }
  
  // 进入模态状态
  enterModal() {
    if (!this.previewPanel) return;
    
    this.isModal = true;
    
    // 保存原始位置和尺寸
    const rect = this.previewPanel.getBoundingClientRect();
    this.originalPosition = {
      top: rect.top,
      left: rect.left,
      width: rect.width,
      height: rect.height
    };
    
    this.previewPanel.classList.add("fullscreen");
    
    // 显示关闭按钮
    if (this.closeBtn) {
      this.closeBtn.style.display = 'flex';
    }
  }
  
  // 退出模态状态
  exitModal() {
    if (!this.previewPanel) return;
    
    this.isModal = false;
    
    // 恢复原始样式
    this.previewPanel.classList.remove("fullscreen");
    
    // 清除可能添加的内联样式
    if (this.previewElement) {
      this.previewElement.style.position = '';
      this.previewElement.style.top = '';
      this.previewElement.style.left = '';
      this.previewElement.style.width = '';
      this.previewElement.style.height = '';
      this.previewElement.style.zIndex = '';
      this.previewElement.style.boxShadow = '';
      this.previewElement.style.borderRadius = '';
      this.previewElement.style.backgroundColor = '';
      this.previewElement.style.padding = '';
      this.previewElement.style.transform = '';
    }
    
    // 隐藏关闭按钮
    if (this.closeBtn) {
      this.closeBtn.style.display = 'none';
    }
  }
  
  // 关闭模态框
  closeModal() {
    // 退出模态状态并重置缩放
    this.exitModal();
    this.resetZoom();
  }
  
  // 更新缩放显示
  updateZoom() {
    if (!this.previewElement) return;
    
    // 应用缩放变换
    const svgElement = this.previewElement.querySelector('svg');
    if (svgElement) {
      // 使用MermaidRenderer的adjustSvgSize方法来处理SVG尺寸
      if (window.mermaidRenderer && typeof window.mermaidRenderer.adjustSvgSize === 'function') {
        // 保存当前缩放值到SVG元素的自定义属性中
        svgElement.setAttribute('data-current-zoom', this.currentZoom);
        // 应用缩放
        svgElement.style.transform = `scale(${this.currentZoom})`;
        svgElement.style.transformOrigin = 'center center';
      } else {
        // 回退到直接修改transform属性
        svgElement.style.transform = `scale(${this.currentZoom})`;
        svgElement.style.transformOrigin = 'center center';
      }
    }
    
    // 更新按钮状态
    this.updateZoomState();
  }
  
  // 更新缩放按钮状态
  updateZoomState() {
    // 更新按钮禁用状态，添加对按钮元素存在性的检查
    if (this.zoomInBtn) {
      this.zoomInBtn.disabled = this.currentZoom >= this.maxZoom;
    }
    if (this.zoomOutBtn) {
      this.zoomOutBtn.disabled = this.currentZoom <= this.minZoom;
    }
    
    if (this.resetZoomBtn) {
      this.resetZoomBtn.disabled = this.currentZoom === 1;
    }
  }
  
  // 获取当前缩放比例
  getZoomLevel() {
    return this.currentZoom;
  }
  
  // 设置缩放比例
  setZoomLevel(zoomLevel) {
    if (zoomLevel >= this.minZoom && zoomLevel <= this.maxZoom) {
      this.currentZoom = zoomLevel;
      
      // 检查模态状态
      if (this.currentZoom > this.modalThreshold && !this.isModal) {
        this.enterModal();
      } else if (this.currentZoom <= this.modalThreshold && this.isModal) {
        this.exitModal();
      }
      
      this.updateZoom();
    }
  }
}

/**
 * 图表代码高亮助手
 */
class CodeHighlightHelper {
  constructor() {
    this.isPrismLoaded = false;
  }
  
  // 检查Prism.js是否已加载
  ensurePrismLoaded() {
    return new Promise((resolve) => {
      if (window.Prism) {
        this.isPrismLoaded = true;
        resolve(window.Prism);
      } else {
        // 等待Prism.js加载
        const checkInterval = setInterval(() => {
          if (window.Prism) {
            clearInterval(checkInterval);
            this.isPrismLoaded = true;
            resolve(window.Prism);
          }
        }, 100);
        
        // 设置超时
        setTimeout(() => {
          clearInterval(checkInterval);
          console.warn('Prism.js加载超时，使用备用样式');
          resolve(null);
        }, 3000);
      }
    });
  }
  
  // 高亮代码
  async highlightCode(code, language = 'mermaid') {
    try {
      const prism = await this.ensurePrismLoaded();
      
      if (prism) {
        // 检查Prism.js是否支持指定语言
        if (prism.languages[language]) {
          // 使用Prism.js进行高亮
          const highlightedCode = prism.highlight(code, prism.languages[language], language);
          return highlightedCode;
        } else {
          // 如果不支持该语言，使用备用高亮方法
          console.warn(`Prism.js不支持语言: ${language}，使用备用高亮方法`);
          return this.applyFallbackHighlighting(code);
        }
      } else {
        // 使用备用高亮方法
        return this.applyFallbackHighlighting(code);
      }
    } catch (error) {
      console.error('代码高亮失败:', error);
      return this.applyFallbackHighlighting(code);
    }
  }
  
  // 应用备用高亮（简单的关键词着色）
  applyFallbackHighlighting(code) {
    // 对代码进行简单的关键词着色
    let highlightedCode = code
      // 图表类型关键字
      .replace(/\b(flowchart|graph|sequenceDiagram|classDiagram|gantt|pie|stateDiagram|erDiagram|mindmap|gitGraph|requirementDiagram|journey|C4Context|C4Container|C4Component|C4Deployment|timeline)\b/g, '<span class="keyword">$1</span>')
      // 图表方向
      .replace(/\b(TD|LR|RL|BT|TB)\b/g, '<span class="meta">$1</span>')
      // 子图定义
      .replace(/\bsubgraph\b/g, '<span class="built_in">subgraph</span>')
      .replace(/\bend\b/g, '<span class="built_in">end</span>')
      // 注释
      .replace(/%%.*$/gm, '<span class="comment">$&</span>')
      // 引号字符串
      .replace(/(["'])(.*?)(\1)/g, '<span class="string">$1$2$3</span>')
      // HTML标签
      .replace(/<[^>]*>/g, '<span class="tag">$&</span>')
      // 样式定义
      .replace(/\b(classDef|style|linkStyle)\b/g, '<span class="attribute">$1</span>')
      // 颜色值
      .replace(/#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/g, '<span class="number">$&</span>')
      .replace(/\b(aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|purple|red|silver|teal|white|yellow)\b/g, '<span class="built_in">$1</span>')
      // 数字
      .replace(/\b\d+(\.\d+)?\b/g, '<span class="number">$&</span>')
      // 操作符
      .replace(/([=\->:\|\&])/g, '<span class="operator">$1</span>');
    
    return highlightedCode;
  }
}

// 导出函数和类
export { debounce, copyCodeToClipboard, ZoomController, CodeHighlightHelper };